import 'package:flutter/material.dart';
import 'package:flutter_app/config.dart';
import 'package:flutter_app/widget/Image_edit.dart';
import 'package:flutter_app/widget/Utils.dart';
import 'package:flutter_app/widget/picture_view.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';

class ImagePage extends StatefulWidget {

  ImagePage({Key key}) : super(key: key);

  final String title = '图库';

  @override
  _MyFirstPageState createState() {
    return new _MyFirstPageState();
  }
}

class _MyFirstPageState extends State<ImagePage> {

  String pageUrl = "${Config.apiHost}/api/img/page?";
  String updateUrl = "${Config.apiHost}/api/img/update?";
  int page = 1;
  int size = 16;
  String title = "";
  String content = "";
  List imgList = [];
  ScrollController _scrollController = new ScrollController();


  void loadData() {
    http.get("${pageUrl}page=$page&size=$size")
        .then((response) =>
        setState(() {
          imgList = json.decode(response.body)['dataList'];
        })
    );
  }

  @override
  void initState() {
    // 上拉加载新一页数据
    _scrollController.addListener((){
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        page++;
        Utils.showToast("正在加载第 $page 页...");
        Future.delayed(Duration(seconds: 2));
        http.get("${pageUrl}page=$page&size=$size")
            .then((response) =>
            setState(() {
              imgList.addAll(json.decode(response.body)['dataList']);
            })
        );
      }
    });
    // 加载初始数据
    loadData();
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
//      appBar: AppBar(
//        title: Text(widget.title),
//      ),
      body: RefreshIndicator(
        child: _buildGrid(),
        onRefresh: _handleRefresh,
      )
    );
  }

  Widget _buildGrid() {
    return GridView.extent(
      maxCrossAxisExtent: 150.0,
      // padding: const EdgeInsets.all(4.0),
      mainAxisSpacing: 4.0,
      crossAxisSpacing: 4.0,
      children: _buildGridTileList(),
      controller: _scrollController,
    );
  }

  List<Container> _buildGridTileList() {

    return List<Container>.generate(
        imgList.length,
        (int index) => Container(
          child: InkWell(
            child: Image(
              image: CachedNetworkImageProvider("${Config.imgHost}/${imgList[index]["url"]}"),
              width: 96.0,
              height: 96.0,
              fit: BoxFit.contain,
            ),
            onTap: () {
              Utils.showToast("点击的序号：$index");
              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return Picture(
                    title: "图片预览",
                    img: Image(
                      image: CachedNetworkImageProvider("${Config.imgHost}/${imgList[index]["url"]}"),
                    ),
                    data: imgList[index],
                );
              }));
            },
            onLongPress: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return EditImageInfo(
                  img: Image(
                    image: CachedNetworkImageProvider("${Config.imgHost}/${imgList[index]["url"]}"),
                  ),
                  data: imgList[index],
                );
              }));
            },
          ),
        )
    );
  }


  Future<Null> _handleRefresh() async {
    Utils.showToast("正在加载...");
    page = 1;
    http.get("${pageUrl}page=$page&size=$size")
        .then((response) =>
        setState(() {
          imgList = json.decode(response.body)['dataList'];
        })
    );
    return null;
  }
}